#!/bin/env python
# -*- coding:utf-8
"""
@author:xingz
@file:get_img.py
@time:2022/05/29
"""
import os.path
import time
from random import randint

import requests

daidai_http = 'https://weibo.com/ajax/statuses/mymblog?uid=3176010690&page=1&feature=0'
cookie = 'SINAGLOBAL=582728378378.2988.1645194825663; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WhIfuPNI76bUd5DiegeHUJq5JpX5KMhUgL.Foz4eo5R1hMXeo22dJLoI7DoIs8V9cy0Ig4r; ULV=1654014945360:18:1:5:3546335138792.4736.1654014945346:1653965577233; PC_TOKEN=e395c8a7cd; ALF=1685590627; SSOLoginState=1654054627; SCF=AqU34R1Ms3CuJgIdcSt9eKA5szbSxXvUDdQPV-7028URaCmxrlMvrLXDI92g28LXxbGSQLkgKpX_A2XiXioQeNU.; SUB=_2A25Pkq60DeRhGeRH6VIZ-CnIyT2IHXVs6Yd8rDV8PUNbmtAfLUOgkW9NTcE9UY1I_k_0ueXHZ6cobtxgzkEgR2TJ; XSRF-TOKEN=B35S7iOL8GRELM8Z2dkExadm; WBPSESS=Uo284Otxbx0FLwJ_Bm-LavnqITnR94as9S6pzrMjPY0pkZAAJzN0LQHeU0f-2GCg0L_Jx3E-Nl90wiGYfKIzJ0JxUjPapfHjuab6kwVmyDLPNlXyaLUSEBVeL-f7LctgoSxmsTvzfQJnVuJvX7hhwg==; SL_G_WPT_TO=zh; SL_GWPT_Show_Hide_tmp=1; SL_wptGlobTipTmp=1'

header = {'accept': "application/json, text/plain, */*", "cookie": cookie}


def get_timestamp(time_str: str):
    time_lst = time_str.split(" ")
    time_str = " ".join(time_lst[:4]) + " " + time_lst[5]
    time_formate = time.strptime(time_str, "%a %b %d %H:%M:%S %Y")
    time_stamp = int(time.mktime(time_formate))
    return time_stamp


def get_timestring(time_str: str):
    time_lst = time_str.split(" ")
    time_str = " ".join(time_lst[:4]) + " " + time_lst[5]
    time_formate = time.strptime(time_str, "%a %b %d %H:%M:%S %Y")
    time_stamp = int(time.mktime(time_formate))
    timestring = time.strftime("%Y%m%d%H%M%S", time_formate)
    return timestring


def get_dddsx_weibo():
    ret = requests.get(url=daidai_http, headers=header)
    all_weibo: list = ret.json()['data']['list']
    all_weibo.sort(key=lambda x: get_timestamp(x['created_at']), reverse=True)
    return all_weibo


def get_weibo_comment(id_str, uid_str):
    latest_comment_utl = f"https://weibo.com/ajax/statuses/buildComments?flow=0&is_reload=1&id={id_str}&is_show_bulletin=2&is_mix=0&count=10&uid={uid_str}"
    comment_ret = requests.get(latest_comment_utl, headers=header)
    all_comment = comment_ret.json()['data']
    return all_comment


def get_dddsx_ymg_pics(weibo_index=0, flow=0):
    all_weibo = get_dddsx_weibo()
    latest_weibo = all_weibo[weibo_index]

    uid_str = latest_weibo['user']['idstr']
    weib_timestring = get_timestring(latest_weibo['created_at'])
    id_str = latest_weibo['idstr']

    all_comment = get_weibo_comment(id_str, uid_str)
    ymg_lst = []
    for comment in all_comment:
        if "玫瑰" in comment['text'] or "内鬼" in comment['text'] or "那个" in comment['text']:
            ymg_lst.append(comment)

    for ymg in ymg_lst:
        ymg_comment_id = ymg['idstr']
        count = 200
        if flow:
            count = 100
        comment_url = f"https://weibo.com/ajax/statuses/buildComments?flow={flow}&is_reload=1&id={ymg_comment_id}&is_show_bulletin=2&is_mix=1&fetch_level=1&max_id=0&count={count}&uid={uid_str}"

        yum_sub_comment = requests.get(comment_url, headers=header)
        yum_sub_comment_dict = yum_sub_comment.json()
        # print(yum_sub_comment_dict)
        pic_num = 0
        for comment in yum_sub_comment_dict['data']:
            if comment.get('url_struct', None):
                for struct in comment.get('url_struct', None):
                    if struct['url_title'] == '查看图片':
                        for pic_id, pic_info in struct['pic_infos'].items():
                            pic_url = pic_info['woriginal']['url']
                            pic_name = pic_url.split('/')[-1]
                            img_dir = f'./imgs/{weib_timestring}'
                            pic_path = os.path.join(img_dir, pic_name)
                            if os.path.exists(pic_path):
                                # print(pic_id, '已存在')
                                continue

                            pic_content = requests.get(pic_url, headers=header).content
                            if not os.path.exists(img_dir):
                                os.makedirs(img_dir)
                            with open(pic_path, 'wb') as f:
                                f.write(pic_content)
                                print(pic_id, '下载完成')
                                pic_num += 1
        print(len(yum_sub_comment_dict['data']), end='')
        if pic_num:
            print('\033[0mget new pic:', pic_num, "\033[0m")


def get_void_pic():
    temp_pic = 'D:/PycharmProjects/algorithm2/zx_wng/imgs/20220523015829/006NS3Wmgy1h2hq0vk4puj30u0141wjd.jpg'
    with open(temp_pic, 'r') as f:
        print(f)


def download_wng_pics(weibo_index=0):
    get_dddsx_ymg_pics(weibo_index=weibo_index, flow=0)
    get_dddsx_ymg_pics(weibo_index=weibo_index, flow=1)


if __name__ == '__main__':
    while 1:
        try:
            download_wng_pics()
            print('.', end='')
        except Exception as e:
            print(e)
        finally:
            sleep_time = randint(5, 10)
            time.sleep(sleep_time)
